package storage

import (
	"codeless/config"
	models "codeless/model"
	"codeless/utils"
	"context"
	"errors"
	"github.com/tencentyun/cos-go-sdk-v5"
	"mime/multipart"
	"net/http"
	"net/url"
	"path/filepath"
	"strings"
)

type CosStorage struct {
}

var cosClient *cos.Client

func init() {
	fs := config.GetAppConfig().Fs
	if fs.Storage == "cos" && fs.Oss.Id != "" {
		u, _ := url.Parse(fs.Oss.RawUrl)
		b := &cos.BaseURL{BucketURL: u}
		cosClient = cos.NewClient(b, &http.Client{
			Transport: &cos.AuthorizationTransport{
				SecretID:  fs.Oss.Id,
				SecretKey: fs.Oss.Key,
			},
		})
	}
}
func (c *CosStorage) Upload(fh *multipart.FileHeader) (*models.RestOss, error) {
	if cosClient == nil {
		return nil, errors.New("上传失败，客户端未初始化")
	}
	file, fer := fh.Open()
	if fer != nil {
		return nil, errors.New("上传失败，文件打开失败")
	}
	defer file.Close()
	// 对象键（Key）是对象在存储桶中的唯一标识。
	fileSuffix := strings.ToLower(filepath.Ext(fh.Filename))
	rId := utils.NewId()
	oss := config.GetAppConfig().Fs.Oss
	if fileSuffix == "" {
		fileSuffix = ".jpg"
	}
	name := rId + fileSuffix
	if oss.Bucket != "" {
		name = oss.Bucket + "/" + name
	}
	burl := oss.RawUrl + "/" + name
	if oss.Cdn != "" {
		burl = oss.Cdn + "/" + name
	}
	// 1.通过字符串上传对象
	_, err := cosClient.Object.Put(context.Background(), name, file, nil)
	if err != nil {
		return nil, err
	} else {
		resp := models.RestOss{
			Code:       0,
			Message:    "",
			Id:         rId,
			ObjectName: name,
			Url:        burl,
		}
		return &resp, nil
	}
}
func (c *CosStorage) UploadPath(path string) (*models.RestOss, error) {
	if cosClient == nil {
		return nil, errors.New("上传失败，客户端未初始化")
	}
	fileSuffix := strings.ToLower(filepath.Ext(path))
	rId := utils.NewId()
	oss := config.GetAppConfig().Fs.Oss
	if fileSuffix == "" {
		fileSuffix = ".jpg"
	}
	name := rId + fileSuffix
	if oss.Bucket != "" {
		name = oss.Bucket + "/" + name
	}
	burl := oss.RawUrl + "/" + name
	if oss.Cdn != "" {
		burl = oss.Cdn + "/" + name
	}
	// 1.通过字符串上传对象
	_, err := cosClient.Object.PutFromFile(context.Background(), name, path, nil)
	if err != nil {
		return nil, err
	} else {
		resp := models.RestOss{
			Code:       0,
			Message:    "",
			Id:         rId,
			ObjectName: name,
			Url:        burl,
		}
		return &resp, nil
	}
}

func (c *CosStorage) Delete(objectName string) error {
	if cosClient == nil {
		return errors.New("上传失败，客户端未初始化")
	}
	_, err := cosClient.Object.Delete(context.Background(), objectName, nil)
	return err
}
